package com.demo.kotlin.ui

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SPUtils
import com.demo.kotlin.BuildConfig
import com.demo.kotlin.Constant
import com.demo.kotlin.R
import com.demo.kotlin.ui.main.MainActivity
import com.puhui.lib.rxjava.RxUtils
import io.reactivex.Observable
import java.util.concurrent.TimeUnit

class SplashActivity : AppCompatActivity() {

    /**android:background="@drawable/splash" 需要设置一下背景，
    否则当该Activity初始化完成界面显示出来时，会出现UI下移一个title高度距离的问题*/
//    override fun getLayoutId() = R.layout.activity_splash

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.transparent))
        BarUtils.setStatusBarVisibility(this, true)
        BarUtils.setStatusBarLightMode(this, true)

//        DataBindingUtil.setContentView<ActivitySplashBinding>(this, R.layout.activity_splash)
        setContentView(R.layout.activity_splash)

        //由于  intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0  会直接finish页面，故下面两行代码提前执行
//        startService(Intent(this, WebProcessService::class.java))

        /**为了防止重复启动多个闪屏页面**/
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
            return
        }

        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
//        appVersionTv.text = "Version${AppUtils.getAppVersionName()}"

        Observable.timer(500, TimeUnit.MILLISECONDS)
            .compose(RxUtils.bindLifeCycle(this))
            .doOnNext { goToMain() }
            .subscribe()
    }

    private fun goToMain() {
        val isFirstRun = SPUtils.getInstance()
            .getString(Constant.LAST_APP_VERSION, "0.0.0") != BuildConfig.VERSION_NAME
        if (isFirstRun) {
//            ActivityUtils.startActivity(WelcomeActivity::class.java)
            ActivityUtils.startActivity(MainActivity::class.java)
        } else {
            ActivityUtils.startActivity(MainActivity::class.java)
        }
//        finish()  //???为什么finish()后，如果APP处于启动状态，从H5唤起时，就无法打开SplashActivity
    }

}